import 'package:bluetooth_protocols_parser_plugin/library.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/pages/mixin/http_request_mixin.dart';
import 'package:inmotion_pro/pages/mixin/protocol_mixin.dart';
import 'package:inmotion_pro/pages/models/http_response/vehicle_info_detail_response_model.dart';

import '../../../../l10n/local.dart';
import '../../../../service/global_service.dart';
import '../../../others/common_enum/cell_setting_type.dart';
import '../../../mixin/vehicle_type_mixin.dart';
import '../../../models/settting_item_model.dart';
import 'state.dart';

// 关于车辆控制器
class AboutVehicleController extends GetxController
    with ProtocolMixin, HttpRequestMixin {
  // 状态
  final AboutVehicleState state = AboutVehicleState();

  // 当前车辆类型
  VehicleType get _vehicleType => GlobalService.to.currentVehicleType;

  // 车辆SN
  String get _sn => GlobalService.to.currentVehicleModel.value.sn;

  @override
  void onInit() {
    super.onInit();

    state.itemList.value = _vehicleType.getAboutVehicleCellList();

    Future.delayed(const Duration(milliseconds: 300), () {
      // 获取车辆信息
      _getVehicleInfo();
    });
  }

  // 刷新设置项
  void _refreshSettingItems(VehicleInfoDetailRspModel info) {
    void setValue(SettingRowModel rowItem) {
      if (rowItem.title == local.sn) {
        rowItem.value = info.sn;
      } else if (rowItem.title == local.bluetooth_name) {
        rowItem.value = info.bluetoothName;
      } else if (rowItem.title == local.model) {
        rowItem.value = info.modelName;
      } else if (rowItem.title == local.activated_date) {
        rowItem.value = info.activatedAtFormatted;
      } else if (rowItem.title == local.human_board) {
        // 更省内存并避免额外创建中间 List，使用简单循环查找匹配项
        String version = "";
        for (final v in info.versions) {
          if (v.deviceId == TargetDeviceType.eucHmic.rawValue) {
            version = v.appVersion;
            break;
          }
        }
        rowItem.value = "V$version";
      } else if (rowItem.title == local.driver_board) {
        // 更省内存并避免额外创建中间 List，使用简单循环查找匹配项
        String version = "";
        for (final v in info.versions) {
          if (v.deviceId == TargetDeviceType.eucDriver.rawValue) {
            version = v.appVersion;
            break;
          }
        }
        rowItem.value = "V$version";
      } else if (rowItem.title == local.bluetooth_board) {
        // 更省内存并避免额外创建中间 List，使用简单循环查找匹配项
        String version = "";
        for (final v in info.versions) {
          if (v.deviceId == TargetDeviceType.eucBle.rawValue) {
            version = v.appVersion;
            break;
          }
        }
        rowItem.value = "V$version";
      } else if (rowItem.title == local.BMS_1) {
        // 更省内存并避免额外创建中间 List，使用简单循环查找匹配项
        String version = "";
        for (final v in info.versions) {
          if (v.deviceId == TargetDeviceType.eucBMS1.rawValue) {
            version = v.appVersion;
            break;
          }
        }
        rowItem.value = "V$version";
      } else if (rowItem.title == local.BMS_2) {
        // 更省内存并避免额外创建中间 List，使用简单循环查找匹配项
        String version = "";
        for (final v in info.versions) {
          if (v.deviceId == TargetDeviceType.eucBMS2.rawValue) {
            version = v.appVersion;
            break;
          }
        }
        rowItem.value = "V$version";
      } else if (rowItem.title == local.display) {
        // 更省内存并避免额外创建中间 List，使用简单循环查找匹配项
        String version = "";
        for (final v in info.versions) {
          if (v.deviceId == TargetDeviceType.eucDc.rawValue) {
            version = v.appVersion;
            break;
          }
        }
        rowItem.value = "V$version";
      } else if (rowItem.title == local.tbox_set) {
        // 更省内存并避免额外创建中间 List，使用简单循环查找匹配项
        String version = "";
        for (final v in info.versions) {
          if (v.deviceId == TargetDeviceType.eucTBox.rawValue) {
            version = v.appVersion;
            break;
          }
        }
        rowItem.value = "V$version";
      }
    }

    // 优化：使用递归方式遍历所有子项，减少嵌套循环
    void updateItems(List<SettingRowModel> items) {
      for (var rowItem in items) {
        setValue(rowItem);
        if (rowItem.subItems.isNotEmpty) {
          updateItems(rowItem.subItems);
        }
      }
    }

    for (var item in state.itemList) {
      updateItems(item.subItems);
    }
    state.itemList.refresh();
  }

  // 获取车辆信息
  Future<void> _getVehicleInfo() {
    httpRequestMixinRequestVehicleInfoDetail(
      _sn,
      (p0) {
        state.vehicleInfoDetail.value = p0.$1;
        _checkOwnersInfo(p0.$1);
        _refreshSettingItems(p0.$1);
      },
      onError: (err) {},
    );
    return Future.value();
  }

  // 检查车主信息
  _checkOwnersInfo(VehicleInfoDetailRspModel info) {
    // 先移除已有的车主信息分区，避免重复添加
    state.itemList.removeWhere(
      (section) => section.sectionType == CellSectionType.ownerInfo,
    );
    // 如果存在车主信息，则更新状态
    if (info.owners.isNotEmpty) {
      // 根据车主类型排序，主车主在前面
      info.owners.sort((a, b) => a.ownerType.val - b.ownerType.val);
      state.itemList.add(
        SettingSectionModel(
          sectionType: CellSectionType.ownerInfo,
          subItems: [
            for (var i = 0; i < info.owners.length; i++)
              SettingRowModel(
                rowType: CellRowType.onlyValue,
                title: i == 0 ? local.primary_owner : "${local.co_owner} $i",
                value:
                    "${info.owners[i].nickname.isEmpty ? info.owners[i].name : info.owners[i].nickname}${info.owners[i].uid == GlobalService.to.cacheUserInfo.value.uid ? " (${local.me})" : ""}",
              ),
          ],
        ),
      );
    }
  }
}
